<?php
namespace app\shop\controller\admin;
use app\admin\library\AdminController;
use app\shop\library\ApiController;

class Goods extends AdminController{
    public function onIndex(){
        $this->power('shop.goods');
        $this->pageTitle = '商品管理';
        $this->pageIcon = 'fa-diamond';

        $goods =  $this->model('Goods');

        $this->set('statusList',$goods->defineStatus());

        return $this->display();
    }

    public function onList(){

        $page_current = $this->post('page_current',$this->check()->type('int')->default(1));
        $cate_id = $this->post('cate_id',$this->check()->type('int'));
        $keyword = $this->post('keyword',$this->check()->type('string'));

        $goods =  $this->model('Goods');

        if ($cate_id){
            $cate = $this->model('Cate');
            $goods->where('cate_id','in',$cate->getKeyCollect($cate_id));
        }

        if ($keyword){
            $goods->where([
                ['title','like','%'.$keyword.'%'],
                ['goods_id',$keyword]
            ]);
        }

        $page_size  =  30;
        
        $list  =  $goods->page($page_current,$page_size)->order('sort','desc')->getData();

        foreach ($list as &$item){
            $item = $goods->formate($item);
            
        }

        $re = [
            'list'=>$list,
            'total'=>$goods->total,
            'count'=>$goods->pageCount,
        ];

        return $re;
    }


    public function onEdit(){
        $this->power('shop.goods');
        $id = $this->get('id',$this->check('ID')->type('int'));
        $this->pageTitle = '添加商品';
        if ($id){
            $this->pageTitle = '编辑商品';
            $Goods = $this->model('Goods');
            $data = $Goods->getId($id);
            if ($data['sku_param']){
                $data['sku_param'] = json_decode($data['sku_param'],true);
                
                $goodsSku = $this->model('GoodsSku');
                $this->set('sku',$goodsSku->field('indexs,name,title,price,weight,stock,barcode,default_value')->where('goods_id',$id)->getData());
            }

            $GoodsDetail = $this->model('GoodsDetail')->getId($id);
            if ($GoodsDetail) $data['content'] =  $GoodsDetail['content'];
            $this->set('goods',$data);
        }

        return $this->display();
    }


    public function onSave(){
        $goods_id = $this->post('goods_id',$this->check()->type('int'));

        $data['cate_id'] =  $this->post('cate_id',$this->check()->type('int')->required());
        $data['title'] =  $this->post('title',$this->check()->type('string')->required());
        $data['picture'] = $this->post('picture',$this->check()->type('string')->required());
        $pictures = explode(',', $data['picture']);
        $data['picture_main'] = $pictures[0];
        $data['model_id'] = $this->post('model_id',$this->check()->type('int'));
        $data['model_value']  = json_encode($this->post('model_value',[]));
        $data['spec_id'] =  $this->post('spec_id',$this->check()->type('int'));
        $data['variant_id'] =  $this->post('variant_id',$this->check()->type('int'));
        
        $data['spec']   = json_encode($this->post('spec',[]));
 
        $sku = null;
        if ($data['variant_id']!=''){

            $sku_param =  $this->post('sku_param',$this->check()->type('array')->required());

            $data['sku_param'] = json_encode($sku_param);

            $sku = $this->post('sku',[]);

            if (count($sku)==0){
                throw new \Exception('请填写正确的规格');
            }

            foreach($sku as $skuItem){

                if (!isset( $skuItem['weight'])){
                    $skuItem['weight'] = '';
                }

                if (is_null($skuItem['price']) || is_null($skuItem['stock'])){
                    throw new \Exception('请填写正确的规格');
                }

                if (isset($skuItem['default_value']) && $skuItem['default_value']==1){
                    $data['barcode'] = $skuItem['barcode'];
                    $data['price']   = $skuItem['price'];
                    $data['stock']   = $skuItem['stock'];
                    $data['weight']  = $skuItem['weight'];
                }
            }
            
            $data['sku_hash'] = md5(json_encode($sku));
        }else{
            $data['barcode'] =  $this->post('barcode',$this->check()->type('string')->required());
            $data['price']   =  $this->post('price',$this->check()->type('float')->required());
            $data['stock']   =  $this->post('stock',$this->check()->type('int')->required());
            $data['weight']  =  $this->post('weight',$this->check()->type('int'));
            $data['sku_hash'] = '';
        }

        $goods = $this->model('Goods');
        $oldSkuHash = '';
        $GoodsDetail = $this->model('GoodsDetail');
        $content = $this->post('content',$this->check()->type('string'));
        
        if ($goods_id){
            
            $oldData =  $goods->getId($goods_id);
            $updated_at = $this->post('updated_at',$this->check()->type('string')->required());
            $oldSkuHash = $oldData['sku_hash'];
            if ($updated_at != $oldData['updated_at']){
                throw new \Exception('数据已修改，请刷新页面后重试');
            }

            if ($goods->updateId($goods_id,$data)){
                //更新库存
                
                $GoodsDetail->updateId($goods_id,[
                    'content' => $content,
                ]);
            }else{
                throw new \Exception('保存失败');
            }

        }else{

            $data['status'] = 'off';

            if ($goods_id = $goods->insert($data)){
                $GoodsDetail->insert([
                    'goods_id' => $goods_id,
                    'content' => $content,
                ]);
            }else{
                throw new \Exception('保存失败');
            }
        }
        
        if ($sku && $data['sku_hash']!=$oldSkuHash){
           //获取全部的sku
           $goodsSku = $this->model('GoodsSku');

           $list = $goodsSku->where('goods_id',$goods_id)->getData();

           foreach($list as $item){
               //找出sku相对应的记录
               $d = null;
               foreach($sku as $key=>$skuItem){
                   if ($item['name'] == $skuItem['name']){
                       $d = $skuItem;
                       unset($sku[$key]);
                       break;
                   }
               }

               if ($d){
                   $goodsSku->updateId($item['sku_id'],[
                       'price' => $d['price']??0,
                       'stock' => $d['stock']??0,
                       'weight' => $d['weight']??'',
                       'title' => $d['title']??'',
                       'barcode' => $d['barcode']??'',
                       'indexs' => $d['indexs']??'',
                       'default_value'=>$d['default_value']??0
                    ]);

               }else{
                   $goodsSku->deleteId($item['sku_id']);
               }
           }


           if (count($sku)>0){
               foreach($sku as $item){
                   $goodsSku->insert([
                       'goods_id' => $goods_id,
                       'name' => $item['name'],
                       'price' => $item['price'],
                       'stock' => $item['stock']??'',
                       'weight' => $item['weight']??'',
                       'title' => $item['title']??'',
                       'barcode' => $d['barcode']??'',
                       'indexs' => $d['indexs']??'',
                       'default_value'=>$d['default_value']??0
                   ]);
               }
           }
        }

        return true;
    }


    public function onStatus(){
        $goods_id = $this->post('goods_id',$this->check()->type('int')->required());
        $status  = $this->post('status',$this->check()->type('string')->required());

        $goods = $this->model('Goods');
 
        $data = $goods->getId($goods_id);

        if (!$data){
            throw new \Exception('商品不存在');
        }
        $cache = $this->cache();
        $key = ApiController::cacheName('goods',$goods_id);

        if ($status=='off'){    
            $cache->set($key,'off');
        }else{
            $cache->del($key);
        }

        if ($goods->updateId($goods_id,['status'=>$status,'status_at'=>date('Y-m-d H:i:s')])){
            $this->log('修改商品状态',[
                'goods_id' => $goods_id,
                'status' => $status,
                'status_title' => $goods->getStatusTitle($status),
                'status_at' => date('Y-m-d H:i:s'),
                'title' => $data['title']
            ]);
            
            return true;
        }else{
            throw new \Exception('设置失败');
        }
    }

    public function onDetail(){
        $goods_id = $this->post('goods_id',$this->check('商品ID')->type('int')->required());
        $goods = $this->model('Goods');
        
        $data = $goods->where('goods_id',$goods_id)->getRow();

        if ($data){
            return $goods->formate($data);
        }else{
            throw new \Exception('商品不存在');
        }
    }

    public function onSkuDetail(){
        $goods_id = $this->post('goods_id',$this->check('商品ID')->type('int'));
        $variant_id = $this->post('variant_id',$this->check('型号ID')->type('int')->required());


        $variantItem  =  $this->model('VariantItem');
        
        $re['paramList'] =  $variantItem->where('variant_id',$variant_id)->getList();

        if ($goods_id){
            $goods = $this->model('GoodsSku');
            $re['skuList'] = $goods->where('goods_id',$goods_id)->getData();
        }

        return $re;
    }

    public function onDel(){
        $goods_id = $this->post('goods_id',$this->check('商品ID')->type('int'));

        $goods = $this->model('Goods');
        
        $data = $goods->where('goods_id',$goods_id)->getRow();

        if ($data){
            if ($data['status']=='sale'){
                throw new \Exception('在售商品不能删除，请先下架');
            }
        }else{
            throw new \Exception('商品不存在');
        }


        $db = $this->app->db();
        $db->beginTransaction();

        $goods->deleteId($goods_id);
        $goodsSku = $this->model('GoodsSku');
        $goodsSku->where('goods_id',$goods_id)->delete();

        $GoodsDetail = $this->model('GoodsDetail');
        $GoodsDetail->where('goods_id',$goods_id)->delete();

        try{
            $db->commit();
            return true;
        }catch(\Exception $e){
            $db->rollback();
            throw new \Exception('删除失败');
        }
    }
}